package com.example.demo.interceptor;


import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义拦截器
 */

@Slf4j
public class MyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("【拦截器】处理前");
        request.setAttribute("startTime", System.currentTimeMillis());
        log.info(((HandlerMethod) handler).getBean().getClass().getName());
        // true表示放行，false表示拦截
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("【拦截器】处理中");
        Long start = (Long) request.getAttribute("startTime");
        log.info("【拦截器】耗时：" + (System.currentTimeMillis() - start)+"ms");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("【拦截器】处理后");
        Long start = (Long) request.getAttribute("startTime");
        log.info("【拦截器】耗时：" + (System.currentTimeMillis() - start)+"ms");
    }
}
